// pages/map/map.js
var app=getApp()
var amapFile = require('../../libs/amap-wx.js'); //如：..­/..­/libs/amap-wx.js
var markersData = [];
var MapContext;
var myAmapFun;
var timer;
var startPoint;
var key = '我用的高德地图api,请自己申请把key放这里即可'
Page({
  data: {
    markers: [],
    latitude: '',
    longitude: '',
    mylatitude: '', //我的位置
    mylongitude: '', //我的位置
    textData: {},
    address: '', //当前位置
    clicksTop: 0,
    radiusNum: 1,
    isShowtips: true,
    distance: 0
  },
  onReady: function (e) {
    MapContext = wx.createMapContext('map')
  },
  onShow: function () {},
  onLoad: function () {
    var that = this;
    var sysinfo = wx.getSystemInfoSync();
    console.log('设备信息', sysinfo);
    var query = wx.createSelectorQuery();
    query.select(".map_text").boundingClientRect(function (res) {
      if (!!res) {
        that.setData({
          clicksTop: sysinfo.windowHeight - res.width
        })
      }
    }).exec();

    myAmapFun = new amapFile.AMapWX({
      key: key
    });
    // 获取自身地址
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        that.setData({
          mylatitude: latitude,
          mylongitude: longitude
        });
        myAmapFun.getPoiAround({
          iconPathSelected: '../../assets/home_tab_home_normal.png', //如：..­/..­/img/marker_checked.png
          iconPath: '../../assets/home_tab_home_selected.png', //如：..­/..­/img/marker.png
          success: function (data) {
            markersData = data.markers;
            that.setData({
              markers: markersData,
              latitude: markersData[0].latitude,
              longitude: markersData[0].longitude,
            });
            that.makertap()
          },
          fail: function (info) {
            wx.showModal({
              title: info.errMsg
            })
          }
        })
      }
    })
  },
  makertap(e = {
    markerId: 0
  }, points) {
    let that = this;
    let id = e.markerId;
    // console.log('点击', id);
    // console.log('points', points);
    that.showMarkerInfo(markersData, id);
    that.changeMarkerColor(markersData, id);
    if (!!points) {
      that.setData({
        latitude: points.latitude,
        longitude: points.longitude
      })
    }
    that.calculateDistance()
  },
  inputFun() {
    // myAmapFun.getInputtips({
    //   keywords: "超市",
    //   city: "上海",
    //   location: '',
    //   success: function (data) {
    //     console.log("inputFun", data)
    //     wx.navigateTo({
    //       url: `/pages/mapInfo/mapInfo?infoArray=${encodeURIComponent(JSON.stringify(data))}`,
    //       success: function (res) {},
    //       fail: function (res) {},
    //       complete: function (res) {},
    //     })
    //   }
    // })
    this.setData({
      isShowtips: false
    })
    let selfAddress = {
      address: this.data.address,
      latitude: this.data.latitude,
      longitude: this.data.longitude,
      streetNumber: this.data.streetNumber
    }
    wx.navigateTo({
      url: `/pages/mapInfo/mapInfo?tips=${encodeURIComponent(JSON.stringify(this.data.markers))}&selfAddress=${encodeURIComponent(JSON.stringify(selfAddress))}`,
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  showMarkerInfo(data, i) {
    var that = this;
    if (!!data[i].name && data[i].address) {
      that.setData({
        textData: {
          name: data[i].name,
          desc: data[i].address
        }
      });
    }
    myAmapFun.getRegeo({
      success: (res) => {
        this.setData({
          address: res[0].desc,
          streetNumber: res[0].name,
          latitude: res[0].latitude,
          longitude: res[0].longitude,
        })
      }
    })
    that.calculateDistance()
  },
  changeMarkerColor(data, i) {
    var that = this;
    var markers = [];
    for (var j = 0; j < data.length; j++) {
      if (j == i) {
        data[j].iconPath = "../../assets/home_tab_home_selected.png";
        data[j].width = 44;
        data[j].height = 44;
        data[j].zIndex = 999
      } else {
        data[j].iconPath = "../../assets/home_tab_home_normal.png";
        data[j].width = 22;
        data[j].height = 22;
        data[j].zIndex = 1
      }
      markers.push(data[j]);
    }
    that.setData({
      markers: markers
    });
  },
  // 获取我的位置
  getMyMap(e) {
    let that = this
    //自行查询经纬度 http://www.gpsspg.com/maps.htm
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        MapContext.moveToLocation({
          longitude: longitude,
          latitude: latitude,
        })
        that.setData({
          // latitude: latitude,
          // longitude: longitude,
          mylatitude: latitude,
          mylongitude: longitude
        })
      }
    })
  },
  changeBj(e) {
    console.log(e)
    let that = this
    let radiusNum = that.data.radiusNum
    switch (radiusNum) {
      case 1:
        radiusNum = 5
        break;
      case 5:
        radiusNum = 10
        break;
      case 10:
        radiusNum = 1
        break;
    }
    this.setData({
      radiusNum
    })
    let pointslat = this.data.latitude;
    let pointslong = this.data.longitude;
    // let radius = 500/ 1000;
    let range = 180 / Math.PI * radiusNum / 6372.797;
    let lngR = range / Math.cos(pointslat * Math.PI / 180);
    let maxLat = pointslat + range; //最大纬度
    let minLat = pointslat - range; //最小纬度
    let maxLng = pointslong + lngR; //最大经度
    let minLng = pointslong - lngR; //最小经度
    console.log('maxLat:' + maxLat)
    console.log('minLat:' + minLat)
    console.log('maxLng:' + maxLng)
    console.log('minLng:' + minLng)
    MapContext.includePoints({
      // padding: [100, 20, 300, 20],
      points: [{
          latitude: maxLat,
          longitude: maxLng
        },
        {
          latitude: minLat,
          longitude: minLng
        }
      ]
    })
  },
  // 计算距离
  getDistance(lat1, lng1, lat2, lng2) {
    // lat1用户的纬度
    // lng1用户的经度
    // lat2商家的纬度
    // lng2商家的经度
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    //  s = Math.round(s * 10000) / 10000;
    // s = s.toFixed(1) //保留两位小数
    s = Math.round(s * 10000) / 10;
    // console.log('经纬度计算的距离:' + s)
    return s
  },
  //计算距离我的距离
  calculateDistance() {
    let [
      that,
      latitude,
      longitude,
      mylatitude,
      mylongitude
    ] = [
      this,
      this.data.latitude,
      this.data.longitude,
      this.data.mylatitude,
      this.data.mylongitude
    ]
    console.log('latitude:' + latitude)
    console.log('longitude:' + longitude)
    console.log('mylatitude:' + mylatitude)
    console.log('mylongitude:' + mylongitude)
    let distance = that.getDistance(latitude, longitude, mylatitude, mylongitude)
    console.log('距自己距离', distance)
    that.setData({
      distance
    })
  }
})